<?php
namespace App\Financeiro\Controller;

use Foxframe\Paginator;

use Foxframe\Filter;

use Foxforms\Widget\Field\TextArea;

use Foxforms\Widget\Field\Radio;

use Foxforms\Widget\Field\Select;

use Foxforms\Widget\Field\Input;

use Foxforms\Widget\Form;

class lancamentoController extends \Foxframe\Controller
{
	public function viewListar($params = array())
	{
		$lista	= $this->em->getRepository('\Entities\Financeiro\Lancamento')->findAll();
		$this->view->assign('lista', $lista);
	}

	public function viewSalvarLancamento($params = array())
	{
		if (isset($params['id']) && !empty($params['id']))
			$lancamento	= $this->em->find('\Entities\Financeiro\Lancamento', $params['id']);
		else
			$lancamento	= new \Entities\Financeiro\Lancamento();

		$form	= new Form();
		$form->addValues($lancamento, 'lancamento');
		$form->addElement(Input::create('application')->setType('hidden')->setValue('financeiro'));
		$form->addElement(Input::create('controller')->setType('hidden')->setValue('lancamento'));
		$form->addElement(Input::create('method')->setType('hidden')->setValue('saveSalvarLancamento'));
		$form->addElement(Input::create('lancamento[idlancamento]')->setType('hidden'));
		$form->addElement(Input::create('lancamento[dsnome]')->setLabel('Nome')->validate()->addClass('input-xxlarge'));
		$form->addElement(Input::create('lancamento[vllancamento]')->setType('text')->setLabel('Valor')->validate()->addClass('money'));
		$form->addElement(Input::create('lancamento[dtcompetencia]')->setType('text')->setLabel('Competência')->validate()->addClass('datepicker'));
		$form->addElement(Input::create('lancamento[dtvencimento]')->setType('text')->setLabel('Vencimento')->validate()->addClass('datepicker'));
		$form->addElement(
				Select::create('lancamento[tpnatureza]')
				->setOption(array('C' => 'Crédito', 'D' => 'Débito'))
				->setLabel('Natureza')
				->validate()
			);
		$form->addElement(
				Radio::create('lancamento[flstatus]')
				->setOption(array('1' => 'Efetivado', '0' => 'Pendente'))
				->setLabel('Status')
				->validate()
			);
// 		$form->addElement(
// 				Select::create('lancamento[conta]')
// 				->setOption($this->em->getRepository('\Entities\Financeiro\Conta')->listCombo())
// 				->setLabel('Conta')
// 				->setPlaceHolder('--Selecione--')
// 				->validate()
// 				->addClass('input-xlarge')
// 			);
		$form->addElement(
				Select::create('lancamento[categoria]')
				->setOption($this->em->getRepository('\Entities\Financeiro\Categoria')->listCombo($lancamento->get('tpnatureza')))
				->setLabel('Categoria')
				->setPlaceHolder('--Selecione--')
				->validate()
				->addClass('select2 input-xxlarge')
			);
		$form->addElement(
				Select::create('lancamento[agente]')
				->setOption($this->em->getRepository('\Entities\Corp\Pessoa')->listCombo())
				->setLabel('Agente')
				->setPlaceHolder('--Selecione--')
				->validate()
				->addClass('select2 input-xxlarge')
			);
		$form->addElement(TextArea::create('lancamento[dsobservacao]')->setLabel('Observação')->addClass('input-xxlarge')->setRows(5));
		$form->addElement(Input::create('salvar')->setType('submit')->setValue('Salvar')->addClass(array('btn','btn-primary')));
		$this->view->assign('form', $form);
	}

	public function saveSalvarLancamento($params = array())
	{
		try
		{
			if (isset($params['lancamento']['idlancamento']) && !empty($params['lancamento']['idlancamento']))
				$lancamento	= $this->em->find('\Entities\Financeiro\Lancamento', $params['lancamento']['idlancamento']);
			else
				$lancamento	= new \Entities\Financeiro\Lancamento();

// 			$lancamento->setConta($this->em->find('\Entities\Financeiro\Conta', $params['lancamento']['conta']));
			$lancamento->setCategoria($this->em->find('\Entities\Financeiro\Categoria', $params['lancamento']['categoria']));
			$lancamento->setNome($params['lancamento']['dsnome']);
			$lancamento->setObservacao($params['lancamento']['dsobservacao']);
			$lancamento->setStatus($params['lancamento']['flstatus']);
			$lancamento->setVencimento(\DateTime::createFromFormat('d/m/Y', $params['lancamento']['dtvencimento']));
			$lancamento->setValor($params['lancamento']['vllancamento']);
			$lancamento->setNatureza($params['lancamento']['tpnatureza']);

			if (isset($params['lancamento']['agente']) && !empty($params['lancamento']['agente']))
				$lancamento->setAgente($this->em->find('\Entities\Corp\Pessoa', $params['lancamento']['agente']));


			$this->em->persist($lancamento);
			$this->em->flush();

			$this->setFlash('Success', 'Sucesso', "Lançamento salvo com sucesso");
		}
		catch (\Exception $e)
		{
			$this->setFlash('Error', 'Erro', $e->getMessage());
		}
		$this->redirect($this->uri->getOrigem());
	}

	public function viewListarCredito($params)
	{
		$criteria	= array(
				'l.tpnatureza'	=> "'C'",
		);
		$filter = new Filter($criteria);
		$query = $this->em->getRepository('\Entities\Financeiro\Lancamento')->listar($filter->getQueryFilter());
		if (isset($params['page']))
			$filter->setActualPage($params['page']);

		$paginator = new Paginator($query, $filter->getActualPage(), $filter->getMaxResults(), $this->uri->getUrl().'/page/');

		$this->view->assign('paginator', $paginator);

		if (isset($params['page']))
			return $this->returnAjax(null,null,'viewGridLancamento');
	}

	public function viewListarDebito($params)
	{
		$criteria	= array(
				'l.tpnatureza'	=> "'D'",
		);
		$filter = new Filter($criteria);
		$query = $this->em->getRepository('\Entities\Financeiro\Lancamento')->listar($filter->getQueryFilter());
		if (isset($params['page']))
			$filter->setActualPage($params['page']);

		$paginator = new Paginator($query, $filter->getActualPage(), $filter->getMaxResults(), $this->uri->getUrl().'/page/');

		$this->view->assign('paginator', $paginator);

		if (isset($params['page']))
			return $this->returnAjax(null,null,'viewGridLancamento');
	}

	public function viewListarPeriodo($params)
	{
		$atualDay	= date('w');
		$dateIni	= new \DateTime();
		if ($atualDay > 0)
			$dateIni->add(\DateInterval::createFromDateString("- {$atualDay} days"));

		$dateFim	= new \DateTime();
		if ($atualDay > 0)
			$dateFim	= $dateFim->add(\DateInterval::createFromDateString("- {$atualDay} days"));
		$dateFim->add(\DateInterval::createFromDateString("6 days"));

		$criteria	= array(
			'dtinicial'	=> $dateIni->format('d/m/Y'),
			'dtfinal'	=> $dateFim->format('d/m/Y'),
		);

		$filter = new Filter(isset($params['filter']) ? $params['filter'] : null);
		if (!count($filter->getQueryFilter()))
			$filter->setFilter($criteria);

		$query = $this->em->getRepository('\Entities\Financeiro\Lancamento')->listar($filter->getQueryFilter());
		if (isset($params['page']))
			$filter->setActualPage($params['page']);

		$paginator = new Paginator($query, $filter->getActualPage(), $filter->getMaxResults(), $this->uri->getUrl().'/page/');


		$form	= new Form();
		$form->addValues($filter, 'filter');
		$form->addElement(Input::create('application')->setType('hidden')->setValue('financeiro'));
		$form->addElement(Input::create('controller')->setType('hidden')->setValue('lancamento'));
		$form->addElement(Input::create('method')->setType('hidden')->setValue('viewListarPeriodo'));
		$form->addElement(Input::create('filter[dtinicial]')->setType('text')->setLabel('Data inicial')->addClass('datepicker'));
		$form->addElement(Input::create('filter[dtfinal]')->setType('text')->setLabel('Data inicial')->addClass('datepicker'));
		$form->addElement(Input::create('pesquisar')->setType('submit')->setValue('Pesquisar')->addClass(array('btn','btn-primary')));

		$this->view->assign('paginator', $paginator);
		$this->view->assign('form', $form);

		if (isset($params['page']))
			return $this->returnAjax(null,null,'viewGridLancamento');
	}
}